# files_v2 = open("F:/autodrive_data/meta/carla_challenge_6.scenic","r")
# lines = files_v2.readlines()
# print(type(lines))
# for line in lines:
#     print(line)
# files_v3 = open("F:/autodrive_data/meta/mutant_carla_challenge_6.scenic","w")
# files_v3.writelines(lines)
# #print (files_v2.readline())
# files_v2.close()
# files_v3.close()
import gc
import re
import os
import shutil
import time
import subprocess
import sys
import random
# list = ['D:/Anaconda/envs/Scenic','D:/Anaconda/envs/Scenic/Library/mingw-w64/bin','D:/Anaconda/envs/Scenic/Library/usr/bin','D:/Anaconda/envs/Scenic/Library/bin','D:/Anaconda/envs/Scenic/Scripts','D:/Anaconda/envs/Scenic/bin','D:/Anaconda/condabin','C:/ProgramData/Oracle/Java/javapath','C:/Windows/system32','C:/Windows','C:/Windows/System32/Wbem','C:/Windows/System32/WindowsPowerShell/v1.0','C:/Windows/System32/OpenSSH','C:/Program Files (x86)/NVIDIA Corporation/PhysX/Common','C:/Program Files/NVIDIA Corporation/NVIDIA NvDLISR','C:/WINDOWS/system32','C:/WINDOWS;C:/WINDOWS/System32/Wbem','C:/WINDOWS/System32/WindowsPowerShell/v1.0','C:/WINDOWS/System32/OpenSSH;D:/Program Files (x86)/Git/cmd','D:/Program Files/Java/jdk1.8.0_66/bin','D:/Program Files/Java/jdk1.8.0_66/jre/bin','C:/Program Files (x86)/Windows Kits/8.1/Windows Performance Toolkit','C:/Program Files/Cppcheck;E:/MinGW-W64/mingw64/bin','C:/Users/LZ/AppData/Local/Microsoft/WindowsApps','C:/Program Files/Bandizip','D:/PyCharm 2019.3.3/bin']
# for i in list:
#     #i.replace("\","/")
#     sys.path.append(i)
# sys.path.append('D:/Anaconda/envs/scenic/Lib/site-packages')
# sys.path.append('D:/Anaconda/envs/scenic/Library/bin')
# sys.path.append('D:/Anaconda/envs/scenic/Scripts')
sys.path.append('D:/carla/VerifAI-master/PythonAPI/carla/agents')
sys.path.append('D:/carla/VerifAI-master/verifai')
os.chdir('D:\Anaconda\envs\Scenic\Lib\site-packages\shapely\DLLs')
sys.path.append('D:/Anaconda/envs/Scenic/Lib/site-packages/numpy')
sys.path.append('D:/Anaconda/Library/bin')
sys.path.append('D:/Anaconda/Library/Scripts')
sys.path.append('D:/Anaconda')

# sys.path.append('D:/Anaconda/envs/Scenic/Library/bin')
#获取匹配到的id和下标
def get_items_idx(match_obj, with_words: bool = True) -> dict:
    """ 获取下标
    Parameters
    ----------
    :param match_obj: 匹配之后的对象
    :param with_words: bool (default=True), 是否需要返回对应的单词（默认为True）
    :return: dict of list. 返回的格式{"idx": [], "words": []}
    """
    ret = dict()
    ret["idx"] = []
    ret["words"] = []
    if match_obj:
        for obj in match_obj:
            print(obj.start(),obj.end())
            #print(obj.groups())
            item_num = len(obj.groups())
            for idx in range(1, item_num+1):
                ret["idx"].append(obj.span(idx))
                if with_words:
                    ret["words"].append(obj.group(idx))
    else:
        print("failed!")
    print(ret)
    return ret
#修改地图
def map_mutate(filepath):
    list = ['Town01.xodr','Town02.xodr','Town03.xodr','Town04.xodr','Town05.xodr','Town06.xodr','Town07.xodr','Town10.xodr']
    file1 = open(filepath, "r")
    filepath_before = filepath.split('/')
    for i,e in enumerate(filepath_before):
        if i >len(filepath_before)-3:
            break
        if i == 0:
            filepath_after = e
        else:
            filepath_after = filepath_after + '/' + e
    print(filepath_before)
    print(filepath_after)
    # file1 = open("F:/autodrive_data/meta/carla_challenge_6.scenic","r")
    lines = file1.readlines()
    for i in list:
        flag = True
        newlines = []
        for line in lines:
            if re.match('setMapPath(.*).xodr(.*)',line):
                value = re.match('(.*)Town[0-9][0-9]',line).group().split("'")[1]
                print(value)
                if value not in i:
                    print(2222)
                    # line = line[:22] + i + line[33:]
                    newlines.append(line[:22] + i + line[33:])
                    flag = False
            else:
                newlines.append(line)
        if not flag:
            print(11111)
            print(lines)
            if not os.path.exists(filepath_after + '/mutants_'+filepath_before[-1].split(".")[0]+'/'):  # 若不存在路径则创建
                os.makedirs(filepath_after + '/mutants_'+filepath_before[-1].split(".")[0]+'/')
            if not os.path.exists(filepath_after + '/mutants_' + filepath_before[-1].split(".")[0] + '/'+i.split('.')[0]+'/'):  # 若不存在路径则创建
                os.makedirs(filepath_after + '/mutants_' + filepath_before[-1].split(".")[0] + '/'+i.split('.')[0]+'/')
            shutil.copy('F:/autodrive_data/map/'+i,filepath_after + '/mutants_' + filepath_before[-1].split(".")[0] + '/'+i.split('.')[0]+'/')
            file2 = open(filepath_after + '/mutants_' + filepath_before[-1].split(".")[0] + '/'+i.split('.')[0]+'/'+i.split('.')[0]+'.scenic',"w")
            file2.writelines(newlines)
    #print (files_v2.readline())
    file1.close()
    file2.close()
#获取地图名字
def get_map_name(filepath):
    file1 = open(filepath, "r")
    lines = file1.readlines()
    for line in lines:
        if re.match('setMapPath(.*).xodr(.*)', line):
            # 对应修改value
            value = re.match('(.*)Town[0-9][0-9]', line).group().split("'")[1]
    return value
#scenic文件所在路径'F:/autodrive_data/original/carla_challenge_6.scenic'
def coordinate_mutate(filepath,num = 100):
    # list = ['Town01.xodr', 'Town02.xodr', 'Town03.xodr', 'Town04.xodr', 'Town05.xodr', 'Town06.xodr', 'Town07.xodr',
    #         'Town10.xodr']
    file1 = open(filepath, "r")
    filepath_before = filepath.split('/')
    for i, e in enumerate(filepath_before):
        if i > len(filepath_before) - 3:
            break
        if i == 0:
            filepath_after = e
        else:
            #获取自动路径
            filepath_after = filepath_after + '/' + e
    print(filepath_before)
    print(filepath_after)
    # file1 = open("F:/autodrive_data/meta/carla_challenge_6.scenic","r")
    lines = file1.readlines()
    for count in range(num):
        newlines = []
        for line in lines:
            if re.match('setMapPath(.*).xodr(.*)',line):
                #对应修改value
                value = re.match('(.*)Town[0-9][0-9]',line).group().split("'")[1]
            if '@' in line:
                line1 = line.split('by')[1]
                #print(line1)
                match_obj = re.finditer(r"\d+\.?\d*",line1,re.M | re.I)
                num_list = []
                newline = ''
                #for i,obj in enumerate(match_obj):
                i = 0
                list_obj = []
                for obj in match_obj:
                    list_obj.append(obj)
                    print(obj)
                for obj in list_obj:
                    print(type(obj.start()), obj.end())
                    num_list.append(float(line1[int(obj.start()):int(obj.end())])*random.uniform(0.5,2)+random.uniform(-1,1))
                # for j,e in enumerate(match_dict['idx']):
                #     num_list.append(int(match_dict['words'][j])*random.uniform[0.5,2]+random.uniform[0.5,2])
                    if i == 0:
                        newline = newline + line1[0:int(obj.start())] + str(num_list[i]) + line1[
                                                                                           int(obj.end()) :list_obj[
                                                                                               i+1].start()]
                    elif i<len(list_obj)-1:
                        #暂时无法获取下一个元素
                        newline = newline + str(num_list[i]) + line1[int(obj.end()):list_obj[i+1].start()]
                    else:
                        newline = newline + str(num_list[i]) + line1[int(obj.end()):]
                    i = i + 1
                print(line.split('by')[0])
                newline = line.split('by')[0] + 'by' + newline
                print(newline)
                newlines.append(newline)
            else:
                newlines.append(line)
        print(11111)
        #print(lines)
        if not os.path.exists(filepath_after + '/mutants_coordinate_' + filepath_before[-1].split(".")[0] + '/'):  # 若不存在路径则创建
            os.makedirs(filepath_after + '/mutants_coordinate_' + filepath_before[-1].split(".")[0] + '/')
        if not os.path.exists(filepath_after + '/mutants_coordinate_' + filepath_before[-1].split(".")[0] + '/' + str(count)+ '/'):  # 若不存在路径则创建
            os.makedirs(
                filepath_after + '/mutants_coordinate_' + filepath_before[-1].split(".")[0] + '/' + str(count) + '/')
        #复制地图文件
        shutil.copy('F:/autodrive_data/map/' + value+'.xodr',
                    filepath_after + '/mutants_coordinate_' + filepath_before[-1].split(".")[0] + '/' + str(count) + '/')
        file2 = open(
            filepath_after + '/mutants_coordinate_' + filepath_before[-1].split(".")[0] + '/' + str(count) + '/' +
            str(count) + '.scenic', "w")
        file2.writelines(newlines)
        file2.close()
    # print (files_v2.readline())
    file1.close()
#scenic文件所在路径'F:/autodrive_data/original/carla_challenge_6.scenic'
def angle_mutate(filepath,num = 100):
    file1 = open(filepath, "r")
    filepath_before = filepath.split('/')
    for i, e in enumerate(filepath_before):
        if i > len(filepath_before) - 3:
            break
        if i == 0:
            filepath_after = e
        else:
            # 获取自动路径
            filepath_after = filepath_after + '/' + e
    print(filepath_before)
    print(filepath_after)
    # file1 = open("F:/autodrive_data/meta/carla_challenge_6.scenic","r")
    lines = file1.readlines()
    for count in range(num):
        newlines = []
        for line in lines:
            if re.match('setMapPath(.*).xodr(.*)', line):
                # 对应修改value
                value = re.match('(.*)Town[0-9][0-9]', line).group().split("'")[1]
            #关键字可能还需修改
            if 'deg' in line:
                line1 = line.split('=')[1]
                # print(line1)
                match_obj = re.finditer(r"\d+\.?\d*", line1, re.M | re.I)
                num_list = []
                newline = ''
                # for i,obj in enumerate(match_obj):
                i = 0
                list_obj = []
                for obj in match_obj:
                    list_obj.append(obj)
                    print(obj)
                for obj in list_obj:
                    print(type(obj.start()), obj.end())
                    num_list.append(
                        float(line1[int(obj.start()):int(obj.end())]) * random.uniform(0.5, 2) + random.uniform(-1, 1))
                    # for j,e in enumerate(match_dict['idx']):
                    #     num_list.append(int(match_dict['words'][j])*random.uniform[0.5,2]+random.uniform[0.5,2])
                    if i == 0 and len(list_obj) == 1:
                        newline = newline + line1[0:int(obj.start())] + str(num_list[i]) + line1[
                                                                                           int(obj.end()):]
                    elif i == 0:
                        newline = newline + line1[0:int(obj.start())] + str(num_list[i]) + line1[
                                                                                           int(obj.end()):list_obj[
                                                                                               i + 1].start()]
                    elif i < len(list_obj) - 1:
                        # 暂时无法获取下一个元素
                        newline = newline + str(num_list[i]) + line1[int(obj.end()):list_obj[i + 1].start()]
                    else:
                        newline = newline + str(num_list[i]) + line1[int(obj.end()):]
                    i = i + 1
                print(line.split('=')[0])
                newline = line.split('=')[0] + '=' + newline
                print(newline)
                newlines.append(newline)
            else:
                newlines.append(line)
        print(11111)
        # print(lines)
        if not os.path.exists(
                filepath_after + '/mutants_angle_' + filepath_before[-1].split(".")[0] + '/'):  # 若不存在路径则创建
            os.makedirs(filepath_after + '/mutants_angle_' + filepath_before[-1].split(".")[0] + '/')
        if not os.path.exists(filepath_after + '/mutants_angle_' + filepath_before[-1].split(".")[0] + '/' + str(
                count) + '/'):  # 若不存在路径则创建
            os.makedirs(
                filepath_after + '/mutants_angle_' + filepath_before[-1].split(".")[0] + '/' + str(count) + '/')
        # 复制地图文件
        shutil.copy('F:/autodrive_data/map/' + value + '.xodr',
                    filepath_after + '/mutants_angle_' + filepath_before[-1].split(".")[0] + '/' + str(count) + '/')
        file2 = open(
            filepath_after + '/mutants_angle_' + filepath_before[-1].split(".")[0] + '/' + str(count) + '/' +
            str(count) + '.scenic', "w")
        file2.writelines(newlines)
        file2.close()
    # print (files_v2.readline())
    file1.close()
#filepath1 : scenic文件所在路径  max_try 生成具体场景的数量 filepath2：截图所在的路径，screenshot文件
def mutate_process(filepath1,max_try,filepath2,map = 'Town01'):
    p=subprocess.Popen('D:/carla/WindowsNoEditor/CarlaUE4.exe', close_fds=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    print('carla启动')
    time.sleep(20)
    #先激活python环境再执行
    p1 = subprocess.Popen(
        'conda activate Scenic && D:/Anaconda/envs/Scenic/python.exe D:/carla/VerifAI-master/examples/carla/scenic/scenic_sampler_mutate.py' + ' %s %s' % (
        filepath1, max_try), shell=True, close_fds=True,
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    print('sampler启动')
    #p1 = subprocess.Popen('conda activate Scenic && D:/Anaconda/envs/Scenic/python.exe D:/carla/VerifAI-master/examples/carla/scenic/scenic_sampler_mutate.py'+ ' %s %s' % ('F:/autodrive_data/mutants_carla_challenge_6/Town02/Town02.scenic', 1),shell=True,close_fds=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    # start = time.process_time()
    # while p1.poll() is None:
    #     line = p1.stdout.readline()
    #     line = line.strip()
    #     if line:
    #         print(line)
    #     end = time.process_time()
    #     if end - start > 30:
    #         break
    time.sleep(100)
    #p2 = subprocess.Popen('conda activate Scenic && D:/Anaconda/envs/Scenic/python.exe D:/carla/VerifAI-master/examples/carla/scenic/scenic_simulator_mutate.py'+ ' %s %s' % ("F:/autodrive_data/mutants_carla_challenge_6/Town02/ScreenShot", "Town02"),shell=True,close_fds=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # os.system(
    #     'conda activate Scenic && python D:/carla/VerifAI-master/examples/carla/scenic/scenic_simulator_mutate.py' + ' %s %s' % (
    #     "F:/autodrive_data/mutants_carla_challenge_6/Town02/ScreenShot", "Town02"))
    # os.system('cd D:/carla && conda activate Scenic && python -m VerifAI-master/examples/carla/scenic/scenic_simulator_mutate'+ ' %s %s' % ("F:/autodrive_data/mutants_carla_challenge_6/Town02/ScreenShot", "Town02"))

    #os.system('conda activate Scenic && D:/Anaconda/envs/Scenic/python.exe D:/carla/VerifAI-master/examples/carla/scenic/scenic_simulator_mutate.py'+ ' %s %s' % ("F:/autodrive_data/mutants_carla_challenge_6/Town02/ScreenShot", "Town02"))


    try:
        # 修改
        p2 = subprocess.Popen(
            'cd D:/carla/VerifAI-master && conda activate Scenic && D:/Anaconda/envs/Scenic/python.exe  D:/carla/VerifAI-master/examples/carla/scenic/scenic_simulator_mutate.py' + ' %s %s' % (
                filepath2, map), shell=True, close_fds=True,
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        # 原始
        # os.system(
        # 'cd D:/carla/VerifAI-master && conda activate Scenic && D:/Anaconda/envs/Scenic/python.exe  D:/carla/VerifAI-master/examples/carla/scenic/scenic_simulator_mutate.py' + ' %s %s' % (
        #     filepath2, map))
    except:
        print('生成场景出了些问题')
    else:
        print('生成场景成功')

    # os.system(
    #     'cd D:/carla/VerifAI-master && conda activate Scenic && D:/Anaconda/envs/Scenic/python.exe  D:/carla/VerifAI-master/examples/carla/scenic/scenic_simulator_mutate.py' + ' %s %s' % (
    #     'F:/autodrive_data/mutants_carla_challenge_6/Town02/ScreenShot', 'Town02'))
    #os.system("conda activate Scenic && D:/Anaconda/envs/Scenic/python.exe D:/carla/VerifAI-master/examples/carla/scenic/scenic_sampler.py")
    #os.system('D:/Anaconda/envs/Scenic/python.exe D:/carla/VerifAI-master/examples/carla/scenic/scenic_sampler.py')
#    a = os.system('D:/Anaconda/envs/Scenic/python.exe D:/carla/VerifAI-master/examples/carla/scenic/scenic_sampler.py' + ' %s %s' % (para1, para2))
    #win32api.ShellExecute(0, 'open', r'D:/carla/WindowsNoEditor/CarlaUE4.exe', '', '', 1)
    # stdoutdata, stderrdata = p1.communicate()
    # print(stdoutdata)
    # print(p1.pid)
    # pid = psutil.Process(p1.pid)
    # print(pid.name())
    time.sleep(60*max_try)
    p2.kill()
    p1.kill()
    os.system("taskkill /F /IM CarlaUE4.exe")
    print('carla关闭')
    gc.collect()

    # os.system('D:/carla/WindowsNoEditor/CarlaUE4.exe')
def get_scenic_Path(filepath):
    #for dirpath, dirnames, filenames in os.walk('F:/autodrive_data/meta/ScreenShot'):\
    for dirpath, dirnames, filenames in os.walk(filepath):
        scenic_path = dirnames
        print(scenic_path)
        break
        # print('dirpaath',dirpath)
        # print('dirnames')
        # print(dirnames)
    return scenic_path
def mutate_process_all(filepath):
    scenic_path = get_scenic_Path(filepath)
    for i in scenic_path:
        for dirpath, dirnames, filenames in os.walk(filepath + '/' + i):
            for j in filenames:
                if 'scenic' in j:
                    #暂时按照文件夹来算
                    # try:
                    map_name = get_map_name(filepath + '/' + i + '/' + j)
                    mutate_process(filepath + '/' + i + '/' + j,1,filepath + '/' + i + '/screenShot',map_name)
                    # except:
                    #     print("生成具体场景出现异常")
                    # else:
                    #     print(i+'具体场景生成成功')
                    print(filepath + '/' + i + '/' + j)
                    print(filepath + '/' + i + '/screenShot')
            print(filenames)

if __name__ == '__main__':
    #mutate_process('F:/drive_scene/original/carla_challenge_6.scenic',20,'F:/drive_scene/test_manual/screenShot')

    #map_mutate('F:/autodrive_data/original/carla_challenge_6.scenic')
    #angle_mutate('F:/autodrive_data/original/carla_challenge_6.scenic')
    #coordinate_mutate('F:/autodrive_data/original/carla_challenge_6.scenic')
    #mutate_process()
    #print(get_scenic_Path('F:/autodrive_data/mutants_carla_challenge_6'))

    #mutate_process_all('F:/autodrive_data/mutants_angle_carla_challenge_6')
    #mutate_process_all('F:/autodrive_data/mutants_coordinatecarla_challenge_6')
    #mutate_process_all('F:/autodrive_data/mutants_carla_challenge_6')

    #mutate_process('F:/autodrive_data/original_extend/carla_challenge_6.scenic', 20, 'F:/autodrive_data/original_extend/screenShot')
    #12.31
    #challenge_6
    #蜕变关系验证
    # angle_mutate('F:/drive_scene/original_script/carla_challenge_6.scenic')
    # coordinate_mutate('F:/drive_scene/original_script/carla_challenge_6.scenic')
    # map_mutate('F:/drive_scene/original/carla_challenge_6.scenic')
    #12.31实验对象
    #mutate_process_all('F:/drive_scene/mutants_angle_carla_challenge_6')
    #mutate_process_all('F:/drive_scene/mutants_carla_challenge_6')
    #
    #mutate_process_all('F:/drive_scene/mutants_coordinate_carla_challenge_6')
    # mutate_process_all('F:/drive_scene/mutants_add')
    # mutate_process_all('F:/drive_scene/mutants_del')
    #challenge_7
    # 蜕变关系验证
    # angle_mutate('F:/drive_scene_7/original_script/carla_challenge_7.scenic')
    # coordinate_mutate('F:/drive_scene_7/original_script/carla_challenge_7.scenic')
    # map_mutate('F:/drive_scene_7/original_script/carla_challenge_7.scenic')
    # # 12.31实验对象
    # mutate_process_all('F:/drive_scene_7/mutants_angle_carla_challenge_7')
    # mutate_process_all('F:/drive_scene_7/mutants_carla_challenge_7')
    #
    # mutate_process_all('F:/drive_scene_7/mutants_coordinate_carla_challenge_7')
    # mutate_process_all('F:/drive_scene_7/mutants_add')
    # mutate_process_all('F:/drive_scene_7/mutants_del')
    # # challenge_5
    # # 蜕变关系验证
    # angle_mutate('F:/drive_scene_5/original_script/carla_challenge_5.scenic')
    # coordinate_mutate('F:/drive_scene_5/original_script/carla_challenge_5.scenic')
    # map_mutate('F:/drive_scene_5/original_script/carla_challenge_5.scenic')
    # # 12.31实验对象
    # mutate_process_all('F:/drive_scene_5/mutants_angle_carla_challenge_5')
    # mutate_process_all('F:/drive_scene_5/mutants_carla_challenge_5')
    #
    # mutate_process_all('F:/drive_scene_5/mutants_coordinate_carla_challenge_5')
    # mutate_process_all('F:/drive_scene_5/mutants_add')
    # mutate_process_all('F:/drive_scene_5/mutants_del')
    # ajust
    # 蜕变关系验证
    # angle_mutate('F:/drive_scene_ajust/original_script/adjacentOpposingPair.scenic')
    # coordinate_mutate('F:/drive_scene_ajust/original_script/adjacentOpposingPair.scenic')
    # map_mutate('F:/drive_scene_ajust/original_script/adjacentOpposingPair.scenic')
    # 12.31实验对象
    # mutate_process_all('F:/drive_scene_ajust/mutants_angle_adjacentOpposingPair')
    # mutate_process_all('F:/drive_scene_ajust/mutants_adjacentOpposingPair')
    #
    # mutate_process_all('F:/drive_scene_ajust/mutants_coordinate_adjacentOpposingPair')
    # mutate_process_all('F:/drive_scene_ajust/mutants_add')
    # mutate_process_all('F:/drive_scene_ajust/mutants_del')
    # car
    # 蜕变关系验证
    # angle_mutate('F:/drive_scene_ajust/original_script/adjacentOpposingPair.scenic')
    # coordinate_mutate('F:/drive_scene_ajust/original_script/adjacentOpposingPair.scenic')
    #map_mutate('F:/drive_scene_car/original_script/car.scenic')
    # 实验对象
    # mutate_process_all('F:/drive_scene_ajust/mutants_angle_adjacentOpposingPair')
    # mutate_process_all('F:/drive_scene_ajust/mutants_adjacentOpposingPair')
    #
    #mutate_process_all('F:/drive_scene_car/mutants_car')
    # mutate_process_all('F:/drive_scene/mutants_add')
    mutate_process('F:/drive_scene_5_test/original_script/carla_challenge_5.scenic',10,'F:/drive_scene_5_test/original')


